<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Search } from '@/components/Search'
import { Table, TableColumn } from '@/components/Table'
import { ref, reactive, onMounted, computed, watch, h } from 'vue'
import { FormSchema } from '@/components/Form'
import { useSearch } from '@/hooks/web/useSearch'
import {
  ElTag,
  ElMessage,
  ElUpload,
  ElButton,
  ElRadio,
  ElRadioGroup,
  ElInput,
  ElDialog,
  ElForm,
  ElFormItem
} from 'element-plus'
import { BaseButton } from '@/components/Button'
import { useRouter } from 'vue-router'
import { Dialog } from '@/components/Dialog'
import { Icon } from '@/components/Icon'
import * as XLSX from 'xlsx'
import { CustomSearch } from '@/components/CustomSearch'
import {
  getAbnormalOrderStatsZg,
  exportData,
  updateAbnormalRectification
} from '@/api/electricityAbnormal'
import { useTable } from '@/hooks/web/useTable'
import { custClsOptions, ecCategOptions, deregAttrTypeOptions, abnorCategOptions } from '@/dicts'
import dayjs from 'dayjs'
const { t } = useI18n()
const router = useRouter()

// 整改弹窗相关
const rectificationDialogVisible = ref(false)
const currentRow = ref<any>(null)
const rectificationForm = reactive({
  rectAppNo: '',
  rectSug: '',
  rectStat: '01',
  realRectInfo: ''
})

// 表单校验规则
const rectificationRules = {
  rectStat: [{ required: true, message: '请选择整改状态', trigger: 'change' }],
  realRectInfo: [
    {
      required: false,
      validator: (rule, value, callback) => {
        if (rectificationForm.rectStat === '04' && (!value || value.trim() === '')) {
          callback(new Error('选择"无需处理"时必须填写实际整改说明'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 表单引用
const rectificationFormRef = ref<any>(null)

// 整改状态
const rectStatNum = ref<string>('')
// 打开整改弹窗
const openRectificationDialog = (row) => {
  currentRow.value = row

  // 设置表单数据
  rectificationForm.rectAppNo = row.rectAppNo || row.rectificationNo || ''
  rectificationForm.rectSug = row.rectSug || row.rectificationSuggestion || ''
  rectificationForm.rectStat = row.rectStat || '01' // 使用当前行的状态码，默认为'01'
  rectificationForm.realRectInfo = row.realRectInfo || ''
  rectStatNum.value = row.rectStat
  rectificationDialogVisible.value = true
}

// 提交整改
const submitRectificationForm = async () => {
  if (!rectificationFormRef.value) return

  try {
    // 表单验证
    await rectificationFormRef.value.validate()

    // 准备提交数据
    const submitData = {
      // 可能需要添加其他必要字段
      ...currentRow.value,
      rectStat: rectificationForm.rectStat, // 使用表单中的状态码
      realRectInfo: rectificationForm.realRectInfo
    }
    console.log('提交数据:', submitData)
    // 调用API
    const response = await updateAbnormalRectification([submitData])
    console.log('提交响应:', response)
    if (response && response.code === 200) {
      ElMessage.success(`整改工单已提交成功`)
      rectificationDialogVisible.value = false

      // 刷新表格数据
      getTableData()
    }
  } catch (error) {
    console.error('整改提交失败:', error)
    if (error instanceof Error) {
      ElMessage.warning(error.message)
    } else {
      ElMessage.error('整改提交失败，请重试')
    }
  }
}

// 取消整改
const cancelRectification = () => {
  rectificationDialogVisible.value = false
}

// 搜索相关
const { searchRegister, searchMethods } = useSearch()
const searchRef = ref(null)
const { setSchema, getFormData, setValues } = searchMethods

// 多选相关数据
const selectedRows = ref<any[]>([])

// 处理多选变化
const handleSelectionChange = (selection: any[]) => {
  console.log('selection', selection)
  selectedRows.value = selection
  console.log('选中的行:', selection)
}

// 搜索表单配置
const schema = reactive<FormSchema[]>([
  {
    field: 'mgtOrgName',
    label: '管理单位',
    component: 'Input',
    componentProps: {
      placeholder: '请输入管理单位'
    }
  },
  {
    field: 'expYm',
    label: '量费年月',
    component: 'DatePicker',
    componentProps: {
      type: 'monthrange',
      valueFormat: 'YYYYMM',
      startPlaceholder: '开始年月',
      endPlaceholder: '结束年月',
      size: 'default', // 添加size属性，可选值：large/default/small
      style: { width: '60%' }, // 添加style属性控制宽度
      value: ['202504', '202504']
    }
  },
  // {
  //   field: 'custCls',
  //   label: '客户分类',
  //   component: 'Select',
  //   componentProps: {
  //     placeholder: '请选择客户分类',
  //     options: custClsOptions,
  //     multiple: true,
  //     collapseTags: true,
  //     collapseTagsTooltip: true,
  //     clearable: true
  //   }
  // },
  {
    field: 'deregAttrCls',
    label: '市场化属性分类',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择市场化属性分类',
      props: {
        checkStrictly: false,
        emitPath: false,
        multiple: true,
        children: 'children',
        value: 'value',
        label: 'label'
      },
      options: deregAttrTypeOptions,
      collapseTags: true,
      collapseTagsTooltip: true,
      clearable: true
    }
  },
  {
    field: 'ecCateg',
    label: '用电类别',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择用电类别',
      props: {
        checkStrictly: false,
        emitPath: true,
        multiple: true,
        children: 'children',
        value: 'value',
        label: 'label'
      },
      options: ecCategOptions,
      collapseTags: true,
      collapseTagsTooltip: true,
      clearable: true
    }
  },
  {
    field: 'abnorCateg',
    label: '异常类型',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择异常类型',
      props: {
        checkStrictly: false,
        emitPath: true,
        multiple: true,
        children: 'children',
        value: 'value',
        label: 'label'
      },
      options: abnorCategOptions,
      collapseTags: true,
      collapseTagsTooltip: true,
      clearable: true
    }
  },
  {
    field: 'custNo',
    label: '用户编号',
    component: 'Input',
    componentProps: {
      placeholder: '请输入用户编号'
    }
  }
])

// tab栏相关
const activeTab = ref('00')
const rectStatusValue = ref('') // 声明整改状态变量
const tabList = [
  { key: '00', name: '全部' },
  { key: '01', name: '未处理' },
  { key: '02', name: '处理中' },
  { key: '03', name: '已处理' },
  { key: '04', name: '无需处理' }
]

// 切换tab
const handleTabChange = (tab) => {
  activeTab.value = tab
  rectStatusValue.value = tab === '00' ? '' : tab // 00表示全部，不需要添加到查询条件

  // 先清空表格数据
  tableState.dataList.value = []
  tableState.total.value = 0

  // 重置页码到第一页
  currentPage.value = 1

  console.log('切换到tab:', tab, '，整改状态:', rectStatusValue.value)

  // 加载新数据
  loading.value = true
  setTimeout(() => {
    getTableData()
  }, 50)
}

// 表格相关
const columns: TableColumn[] = [
  // {
  //   field: '',
  //   type: 'selection', // 多选列
  //   width: 60,
  //   selection: true
  // },
  {
    field: 'index',
    type: 'index', // 序号列
    label: '序号',
    width: 60,
    fixed: 'left'
  },
  {
    field: 'rectAppNo',
    label: '整改单编号',
    width: 180,
    fixed: 'left'
  },
  {
    field: 'mgtOrgName',
    label: '管理单位',
    width: 180
  },
  {
    field: 'expYm',
    label: '量费年月',
    width: 120
  },
  {
    field: 'rectStat',
    label: '整改状态',
    width: 130,
    formatter: (row) => {
      // 获取状态名称和样式
      const statusName = getRectStatName(row.rectStat)
      const styleType = getRectStatStyle(row.rectStat)

      return h(ElTag, { type: styleType }, () => statusName)
    }
  },
  {
    field: 'abnorType',
    label: '异常类别',
    width: 130
  },
  {
    field: 'abnorCateg',
    label: '异常类型',
    width: 130
  },
  {
    field: 'abnorDtlInfo',
    label: '异常说明',
    width: 250
  },
  {
    field: 'rectSug',
    label: '整改建议',
    minWidth: 250
  },
  {
    field: 'action',
    label: '操作',
    width: 180,
    fixed: 'right',
    slots: {
      default: (data: any) => {
        return [
          h(
            BaseButton,
            {
              type: 'primary',
              link: true,
              onClick: () => openDetailDialog(data.row)
            },
            '查看详情'
          ),
          h('span', { style: 'margin: 0 5px' }, '|'),
          h(
            BaseButton,
            {
              type: 'warning',
              link: true,
              onClick: () => openRectificationDialog(data.row)
            },
            '整改'
          )
        ]
      }
    }
  }
]

// 表格数据和加载状态
const loading = ref(true)

// 使用useTable hook进行表格数据管理
const { tableRegister, tableMethods, tableState } = useTable({
  immediate: false, // 不立即请求，而是在onMounted中手动请求
  fetchDataApi: async () => {
    try {
      // 获取搜索表单数据
      const formData = await getFormData()
      console.log('整改页面formData:', formData)
      console.log('整改页面量费年月值:', formData.expYm)
      if (formData.ecCateg && formData.ecCateg.length !== 0) {
        formData.ecCateg = formData.ecCateg.flat()
      } else {
        formData.ecCateg = []
      }
      const requestParams = {
        startExpYm: formData.expYm?.[0], //
        endExpYm: formData.expYm?.[1], //
        abnorTypeList: formData.abnorCateg?.map((item) => item[0] || ''), //
        abnorCategList:
          formData.abnorCateg?.length > 0 ? formData.abnorCateg?.map((item) => item[1] || '') : [], //
        deregAttrCls: formData.deregAttrCls, // 市场化属性分类
        // custCls: formData.custCls, //
        ecCateg: formData.ecCateg, //
        mgtOrgName: formData.mgtOrgName,
        custNo: formData.custNo, // 用户编号
        rectStat: rectStatusValue.value, // 添加整改状态
        pageSize: tableState.pageSize.value,
        pageNum: tableState.currentPage.value
        // ...formData // 将查询条件合并到请求参数中
      }
      formData.abnorCateg?.map((item) => {
        if (item[0] == '全部') {
          requestParams.abnorTypeList = []
          requestParams.abnorCategList = []
        } else if (item[0] == '无异常') {
          requestParams.abnorCategList = []
        }
      })
      console.log('发送电费异常整改查询API请求参数:', JSON.stringify(requestParams))
      console.log('请求URL: 192.168.1.18:8081/api/users/queryQtyChargArchInfo')

      // 发送请求
      const response = await getAbnormalOrderStatsZg(requestParams)
      console.log('API响应数据:', response)

      // 处理响应数据
      if (response) {
        // 检查响应数据结构并规范化数据格式，以适应useTable的需求
        let list: any[] = []
        let total = 0

        // 提取数据列表
        if (response.data) {
          // 如果存在data字段
          const responseData = response.data

          if (Array.isArray(responseData)) {
            // 如果data本身是数组
            list = responseData
            // 尝试从响应中获取total
            total = (response as any).total || responseData.length || 0
          } else if (typeof responseData === 'object') {
            // 如果data是对象
            if (responseData.list && Array.isArray(responseData.list)) {
              list = responseData.list
              total = responseData.total || responseData.list.length || 0
            } else if (responseData.records && Array.isArray(responseData.records)) {
              list = responseData.records
              total = responseData.total || responseData.records.length || 0
            } else if (responseData.data && Array.isArray(responseData.data)) {
              list = responseData.data
              total = responseData.total || responseData.data.length || 0
            } else if (responseData.rows && Array.isArray(responseData.rows)) {
              list = responseData.rows
              total = responseData.total || responseData.rows.length || 0
            } else {
              // 最后尝试将整个responseData作为单个记录
              list = [responseData]
              total = 1
            }

            // 如果上面没有找到total，尝试从其他常见字段中查找
            if (!total && typeof responseData.totalCount === 'number') {
              total = responseData.totalCount
            } else if (!total && typeof responseData.count === 'number') {
              total = responseData.count
            }
          }
        } else if (Array.isArray(response)) {
          // 如果响应本身就是数组
          list = response
          total = response.length
        } else if (typeof response === 'object') {
          // 直接从响应对象中查找数据
          const resp = response as any
          if (resp.list && Array.isArray(resp.list)) {
            list = resp.list
            total = resp.total || resp.list.length || 0
          } else if (resp.records && Array.isArray(resp.records)) {
            list = resp.records
            total = resp.total || resp.records.length || 0
          } else if (resp.data && Array.isArray(resp.data)) {
            list = resp.data
            total = resp.total || resp.data.length || 0
          } else if (resp.rows && Array.isArray(resp.rows)) {
            list = resp.rows
            total = resp.total || resp.rows.length || 0
          }

          // 尝试获取总数
          if (!total && typeof resp.totalCount === 'number') {
            total = resp.totalCount
          } else if (!total && typeof resp.count === 'number') {
            total = resp.count
          }
        }

        console.log('处理后的数据:', list.length, '条, 总数:', total)

        // 返回符合useTable要求的格式
        return {
          list,
          total
        }
      }

      return {
        list: [],
        total: 0
      }
    } catch (error: any) {
      console.error('获取数据失败:', error)
      ElMessage.error('获取数据失败: ' + (error instanceof Error ? error.message : '未知错误'))
      return {
        list: [],
        total: 0
      }
    }
  }
})

// 从useTable中解构获取数据和状态
const { dataList, total, currentPage, pageSize } = tableState
const { refresh } = tableMethods

// 获取表格数据
const getTableData = () => {
  refresh()
}

// 导出表格数据
const exportTableData = async () => {
  try {
    // 获取搜索表单数据
    const formData = await getFormData()

    const requestParams = {
      ...formData // 将查询条件合并到请求参数中
    }
    requestParams.startExpYm = formData.expYm?.[0] || ''
    requestParams.endExpYm = formData.expYm?.[1] || ''
    delete requestParams.expYm
    console.log('导出数据请求参数:', JSON.stringify(requestParams))
    console.log('导出请求URL: 192.168.1.18:8081/api/users/export')

    ElMessage.info('正在导出数据，请稍候...')

    // 调用导出API，获取二进制数据
    const response = await exportData(requestParams)

    if (response && response.data) {
      // 创建Blob对象
      const blob = new Blob([response.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })

      // 创建下载链接
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      link.href = url
      link.download = '电费异常整改数据.xlsx'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)

      ElMessage.success('数据导出成功')
    } else {
      ElMessage.error('导出失败，请重试')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

// 搜索处理
const handleSearch = async () => {
  // 使用await确保获取到表单数据
  const formData = await getFormData()
  console.log('搜索条件:', formData)

  // 重置页码到第一页
  currentPage.value = 1

  // 刷新数据
  refresh()
}

// 重置搜索
const handleReset = async () => {
  currentPage.value = 1
  refresh()
}

// 详情弹窗相关
const detailDialogVisible = ref(false)
const currentDetail = ref<any>(null)

// 打开详情弹窗
const openDetailDialog = (row: any) => {
  // 模拟获取更多详细数据
  currentDetail.value = {
    ...row
  }
  detailDialogVisible.value = true
}

// 关闭详情弹窗
const closeDetailDialog = () => {
  detailDialogVisible.value = false
}
// Excel文件上传前的钩子
const beforeUpload = (file: File) => {
  const isExcel =
    file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
    file.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!')
    return false
  }

  // 处理Excel文件导入
  handleImportExcel(file)
  return false // 阻止默认上传行为
}

// 处理Excel导入
const handleImportExcel = (file: File) => {
  // 这里简化导入逻辑，仅演示用途
  ElMessage.success('文件上传成功，数据处理中...')
  setTimeout(() => {
    ElMessage.success('数据导入成功')
    getTableData()
  }, 1000)
}
const { setProps } = tableMethods
// 在组件挂载后注册Search组件
onMounted(() => {
  // 设置固定表格高度 457.8
  setProps({
    height: 458
  })
  // 注册搜索组件
  if (searchRef.value) {
    searchRegister(searchRef.value)

    // 统一设置所有表单项的大小和宽度
    schema.forEach((item) => {
      setSchema([
        {
          field: item.field,
          path: 'componentProps.size',
          value: 'default'
        },
        {
          field: item.field,
          path: 'componentProps.style',
          value: { width: '300px' }
        }
      ])
    })

    // 设置量费年月默认值为上个月
    setValues({
      expYm: getPreviousMonthRange()
    })
    console.log('设置默认量费年月:', getPreviousMonthRange())

    // 使用setTimeout确保默认值已经被应用
    setTimeout(() => {
      // 初始化表格数据
      refresh()
    }, 100)
  } else {
    // 如果searchRef为空，仍然需要刷新数据
    refresh()
  }
})

// 监听搜索条件变化
watch(
  () => getFormData(),
  () => {
    console.log('搜索条件已变更')
  },
  { deep: true }
)

// 获取上个月的起止日期（YYYYMM格式）
const getPreviousMonthRange = () => {
  const currentDate = dayjs()
  const previousMonth = currentDate.subtract(1, 'month')
  const previousMonthStr = previousMonth.format('YYYYMM')
  return [previousMonthStr, previousMonthStr]
}

// 整改状态映射
const rectStatMap = {
  '00': '未处理',
  '01': '未处理',
  '02': '处理中',
  '03': '已处理',
  '04': '无需处理'
}

// 状态名称与样式类型的映射
const rectStatStyleMap = {
  未处理: 'danger',
  处理中: 'warning',
  已处理: 'success',
  无需处理: 'info'
}

// 获取整改状态名称
const getRectStatName = (code: string) => {
  return rectStatMap[code] || '未知状态'
}

// 获取整改状态样式类型
const getRectStatStyle = (code: string) => {
  const statusName = getRectStatName(code)
  return rectStatStyleMap[statusName] || 'info'
}

// 复制文本到剪贴板
const copyText = (text: string, label: string) => {
  if (!text || text.trim() === '') {
    ElMessage.warning(`${label}为空，无法复制`)
    return
  }

  navigator.clipboard
    .writeText(text)
    .then(() => {
      ElMessage.success(`已复制${label}`)
    })
    .catch(() => {
      // 备用复制方法
      const textarea = document.createElement('textarea')
      textarea.value = text
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
      ElMessage.success(`已复制${label}`)
    })
}

// 表格样式，奇行背景色#f6f6f6偶行背景色#ffffff
const tableRowStyle = ({ rowIndex }: { rowIndex: number }) => {
  return rowIndex % 2 === 0 ? { background: '#ffffff' } : { background: '#fcfcfc' }
}

// 修改 formData 的类型定义
interface FormData {
  isRectification: boolean
  [key: string]: any
}

const formData = ref<FormData>({
  isRectification: false
})
</script>

<template>
  <ContentWrap title="电费异常整改">
    <!-- 搜索栏 -->
    <CustomSearch
      ref="searchRef"
      :schema="schema"
      label-width="130px"
      :layout="'bottom'"
      :button-position="'right'"
      :custom-buttons="[
        {
          label: '导出数据',
          type: 'success',
          icon: 'vi-ep:download',
          color: '#286af6',
          onClick: exportTableData
        }
      ]"
      @search="handleSearch"
      @reset="handleReset"
    />

    <!-- 状态选项卡 -->
    <div class="status-tabs">
      <div
        v-for="tab in tabList"
        :key="tab.key"
        :class="['status-tab', { active: activeTab === tab.key }]"
        @click="handleTabChange(tab.key)"
      >
        {{ tab.name }} <span class="tab-count"></span>
      </div>
    </div>
    <div>总计：{{ total }}条数据</div>

    <!-- 表格区域 -->
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :loading="tableState.loading.value"
      :data="dataList"
      :columns="columns"
      row-key=""
      :fit="true"
      :pagination="{
        total: total,
        pageSize: pageSize,
        currentPage: currentPage,
        pageSizes: [10, 20, 50, 100],
        background: true
      }"
      style="
        --el-table-border-color: #cdd7d5;
        --el-table-text-color: #171717;
        --el-table-header-text-color: #585858;
      "
      :header-cell-style="{
        background: '#e5f5f3', // 背景色
        color: '#585858' // 文字颜色
      }"
      :row-style="tableRowStyle"
      @register="tableRegister"
      @refresh="refresh"
      @selection-change="handleSelectionChange"
    />
  </ContentWrap>

  <!-- 整改弹窗 -->
  <Dialog
    v-model="rectificationDialogVisible"
    title="整改"
    width="550px"
    maxHeight="500"
    :fullscreen="false"
  >
    <ElForm
      :model="rectificationForm"
      label-width="100px"
      class="rectification-form"
      ref="rectificationFormRef"
      :rules="rectificationRules"
    >
      <ElFormItem label="工单编号">
        <span>{{ rectificationForm.rectAppNo }}</span>
      </ElFormItem>

      <ElFormItem label="整改建议">
        <ElInput
          v-model="rectificationForm.rectSug"
          type="textarea"
          :rows="3"
          resize="none"
          readonly
          placeholder="暂无整改建议"
        />
        <span class="copy-btn" @click="() => copyText(rectificationForm.rectSug, '整改建议')"
          >复制</span
        >
      </ElFormItem>

      <ElFormItem label="工单状态">
        <ElRadioGroup v-model="rectificationForm.rectStat">
          <ElRadio v-if="rectStatNum != '01'" label="01">未处理</ElRadio>
          <ElRadio v-if="rectStatNum != '02'" label="02">处理中</ElRadio>
          <ElRadio v-if="rectStatNum != '03' && rectStatNum != '04'" label="03">已处理</ElRadio>
          <ElRadio v-if="rectStatNum != '04' && rectStatNum != '03'" label="04">无需处理</ElRadio>
        </ElRadioGroup>
      </ElFormItem>

      <ElFormItem label="实际整改说明">
        <ElInput
          v-model="rectificationForm.realRectInfo"
          type="textarea"
          :rows="3"
          resize="none"
          placeholder="请输入实际整改说明"
        />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <ElButton @click="cancelRectification">取 消</ElButton>
      <ElButton type="primary" @click="submitRectificationForm">提 交</ElButton>
    </template>
  </Dialog>

  <!-- 详情弹窗 -->
  <ElDialog
    v-model="detailDialogVisible"
    title="详情"
    width="70%"
    :before-close="closeDetailDialog"
    destroy-on-close
    class="detail-dialog"
    style=""
  >
    <div class="detail-container">
      <div class="detail-section">
        <div class="detail-title">异常及整改信息</div>
        <div class="detail-info">
          <div class="detail-item">
            <div class="detail-label">整改单编号：</div>
            <div class="detail-value">{{ currentDetail?.rectAppNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">整改状态：</div>
            <div class="detail-value">{{ getRectStatName(currentDetail?.rectStat) }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">异常类别：</div>
            <div class="detail-value">{{ currentDetail?.abnorType }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">异常类型：</div>
            <div class="detail-value">{{ currentDetail?.abnorCateg }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">异常说明：</div>
            <div class="detail-value">{{ currentDetail?.abnorDtlInfo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">整改建议：</div>
            <div class="detail-value">{{ currentDetail?.rectSug }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">实际整改说明：</div>
            <div class="detail-value">{{ currentDetail?.realRectInfo }}</div>
          </div>
        </div>
      </div>
      <div class="detail-section">
        <div class="detail-title">算费信息</div>
        <div class="detail-info">
          <div class="detail-item">
            <div class="detail-label">量费年月：</div>
            <div class="detail-value">{{ currentDetail?.expYm }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">计划编号：</div>
            <div class="detail-value">{{ currentDetail?.planNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">核算包编号：</div>
            <div class="detail-value">{{ currentDetail?.bilgUnitNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">本次抄见量：</div>
            <div class="detail-value">{{ currentDetail?.thisMrQty }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">总结算量：</div>
            <div class="detail-value">{{ currentDetail?.tSettleQty }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">总结算费：</div>
            <div class="detail-value">{{ currentDetail?.tSettleExp }}</div>
          </div>
        </div>
      </div>
      <div class="detail-section">
        <div class="detail-title">本次抄见量</div>
        <div class="reading-table-container">
          <table class="reading-table">
            <thead>
              <tr>
                <td class="table-label">示数类型</td>
                <td v-if="currentDetail?.zxygReadType" class="table-header">正向有功（总）</td>
                <td v-if="currentDetail?.zxygjfReadType" class="table-header">正向有功（尖峰）</td>
                <td v-if="currentDetail?.zxygfReadType" class="table-header">正向有功（峰）</td>
                <td v-if="currentDetail?.zxyggReadType" class="table-header">正向有功（谷）</td>
                <td v-if="currentDetail?.zxygpReadType" class="table-header">正向有功（平）</td>
                <td v-if="currentDetail?.zxwgReadType" class="table-header">正向无功（总）</td>
                <td v-if="currentDetail?.wgReadType" class="table-header">无功（Q4象限）</td>
                <td v-if="currentDetail?.zdxlReadType" class="table-header">最大需量</td>
                <td v-if="currentDetail?.fxwgReadType" class="table-header">反向无功（总）</td>
                <td v-if="currentDetail?.fxygReadType" class="table-header">反向有功（总）</td>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td class="table-label">抄见电量</td>
                <td v-if="currentDetail?.zxygReadType" class="table-cell">{{
                  currentDetail?.zxygReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.zxygjfReadType" class="table-cell">{{
                  currentDetail?.zxygjfReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.zxygfReadType" class="table-cell">{{
                  currentDetail?.zxygfReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.zxyggReadType" class="table-cell">{{
                  currentDetail?.zxyggReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.zxygpReadType" class="table-cell">{{
                  currentDetail?.zxygpReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.zxwgReadType" class="table-cell">{{
                  currentDetail?.zxwgReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.wgReadType" class="table-cell">{{
                  currentDetail?.wgReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.zdxlReadType" class="table-cell">{{
                  currentDetail?.zdxlReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.fxwgReadType" class="table-cell">{{
                  currentDetail?.fxwgReadTypeNameDl || '-'
                }}</td>
                <td v-if="currentDetail?.fxygReadType" class="table-cell">{{
                  currentDetail?.fxygReadTypeNameDl || '-'
                }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      <div class="detail-section">
        <div class="detail-title">基础档案信息</div>
        <div class="detail-info">
          <div class="detail-item">
            <div class="detail-label">管理单位：</div>
            <div class="detail-value">{{ currentDetail?.mgtOrgName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">用户编号：</div>
            <div class="detail-value">{{ currentDetail?.custNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">用户名称：</div>
            <div class="detail-value">{{ currentDetail?.custName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">客户分类：</div>
            <div class="detail-value">{{ currentDetail?.custClsName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">市场化属性分类：</div>
            <div class="detail-value">{{ currentDetail?.deregAttrClsName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">合同容量：</div>
            <div class="detail-value">{{ currentDetail?.ctrtCap }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">运行容量：</div>
            <div class="detail-value">{{ currentDetail?.runCap }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">用电类别：</div>
            <div class="detail-value">{{ currentDetail?.ecCategName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">行业分类：</div>
            <div class="detail-value">{{ currentDetail?.indClsName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">价格码：</div>
            <div class="detail-value">{{ currentDetail?.prcCode }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">定价策略类型：</div>
            <div class="detail-value">{{ currentDetail?.prcStTypeName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">基本电费计算方式：</div>
            <div class="detail-value">{{ currentDetail?.becCalcModeName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">功率因数考核标准：</div>
            <div class="detail-value">{{ currentDetail?.pfStdName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">功率因数考核方式：</div>
            <div class="detail-value">{{ currentDetail?.pfEvalModeName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">电压等级：</div>
            <div class="detail-value">{{ currentDetail?.voltage }}</div>
          </div>
        </div>
      </div>
      <div class="detail-section">
        <div class="detail-title">计量点信息</div>
        <div class="detail-info">
          <div class="detail-item">
            <div class="detail-label">安装点状态：</div>
            <div class="detail-value">{{ currentDetail?.instStatName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">安装点编号：</div>
            <div class="detail-value">{{ currentDetail?.instNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">安装点容量：</div>
            <div class="detail-value">{{ currentDetail?.instCap }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">计量方式：</div>
            <div class="detail-value">{{ currentDetail?.meterModeName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">安装点用途分类：</div>
            <div class="detail-value">{{ currentDetail?.instUsageClsName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">能源计算方式：</div>
            <div class="detail-value">{{ currentDetail?.eCalcModeCodeName }}</div>
          </div>
        </div>
      </div>
      <div class="detail-section-end">
        <div class="detail-title">设备信息</div>
        <div class="detail-info">
          <div class="detail-item">
            <div class="detail-label">表计设备编号：</div>
            <div class="detail-value">{{ currentDetail?.mrDevNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">表计类型：</div>
            <div class="detail-value">{{ currentDetail?.devTypeName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">损耗编号：</div>
            <div class="detail-value">{{ currentDetail?.lossNo }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">变损计算方式：</div>
            <div class="detail-value">{{ currentDetail?.lossAlgFlagName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">调压设备编码：</div>
            <div class="detail-value">{{ currentDetail?.adjDevNo }}</div>
          </div>
        </div>
      </div>
    </div>
  </ElDialog>
</template>

<style lang="scss" scoped>
.rectification-in-progress {
  background-color: #e6f4ff;
  color: #1677ff;
  border-color: #1677ff;
}

.rectification-acceptance {
  background-color: #e6f4ff;
  color: #1677ff;
  border-color: #1677ff;
}

.rectification-form {
  padding: 15px 0;

  .copy-btn {
    margin-left: 10px;
    color: #1677ff;
    cursor: pointer;
  }
}

.table-operations {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}

.operation-button {
  margin-left: 8px;
}

/* 状态选项卡样式 */
.status-tabs {
  display: flex;
  margin-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fff;
  padding: 0 10px;
}

.status-tab {
  padding: 12px 16px;
  cursor: pointer;
  position: relative;
  font-size: 14px;
  color: #606266;
  transition: all 0.3s;
}

.status-tab:hover {
  color: #409eff;
}

.status-tab.active {
  color: #409eff;
  font-weight: 500;
}

.status-tab.active:after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 50%;
  width: 60%;
  height: 2px;
  background-color: #409eff;
  transform: translateX(-50%);
}

.tab-count {
  color: #909399;
  margin-left: 2px;
}

/* 详情弹窗样式 */
.detail-container {
  width: 100%;
  max-height: 70vh;
  overflow-y: auto;
  background-color: #f2f2f2;
  padding: 26px 6px 26px 26px;
}

.detail-section {
  padding: 6px;
  border-bottom: 1px solid #999;
}

.detail-section-end {
  padding: 6px;
}

.detail-title {
  font-size: 18px;
  font-weight: bold;
  margin-top: 4px;
  margin-bottom: 6px;
}

.detail-info {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  justify-content: flex-start;
  padding: 0 0 0 70px;
}

.detail-item {
  width: 33.333%;
  min-height: 30px;
  display: flex;
  padding: 10px;
}

.detail-label {
  font-weight: bold;
  color: #606266;
  // min-width: 130px;
  flex-shrink: 0;
}

.detail-value {
  flex: 1;
  color: #303133;
  word-break: break-all;
}

/* 示数类型表格样式 */
.reading-table-container {
  padding: 0 0 0 70px;
  margin-top: 10px;
}

.reading-table {
  width: 100%;
  border-collapse: collapse;
  /* background-color: #fff; */
  border: 1px solid #dcdfe6;
  font-size: 14px;
}

.reading-table thead {
  /* background-color: #f5f7fa; */
}

.reading-table .table-label {
  /* background-color: #e6f7ff; */
  font-weight: bold;
  color: #303133;
  text-align: center;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  min-width: 80px;
}

.reading-table .table-header {
  /* background-color: #f5f7fa; */
  font-weight: bold;
  color: #606266;
  text-align: center;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  font-size: 13px;
  white-space: nowrap;
}

.reading-table .table-cell {
  text-align: center;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  color: #303133;
  white-space: nowrap;
}
</style>
